package sk.sodik.atomFilter.feeds;

import java.io.Serializable;
import java.net.URL;

import org.w3c.dom.Document;

import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;

public class FeedCache {

	static public final FeedCache instance = new FeedCache();
	private static final long TIMEOUT = 1000 * 3600; // one hour
	private MemcacheService cache;

	private FeedCache() {
		cache = MemcacheServiceFactory.getMemcacheService();
	}

	public Document getFeedForUrl(URL url) {
		CacheEntry entry = (CacheEntry) cache.get(url);
		if (entry == null) {
			return null;
		}
		long age = System.currentTimeMillis() - entry.timestamp;
		if (age > TIMEOUT) {
			return null;
		}
		// not sure, if the cache serialize always -> clone anyway.
		return (Document) entry.document.cloneNode(true);
	}

	public void setFeedForUrl(URL url, Document doc) {
		cache.put(url, new CacheEntry(doc));
	}

	static private class CacheEntry implements Serializable {
		Document document;
		long timestamp;

		public CacheEntry(Document document) {
			super();
			this.document = (Document) document.cloneNode(true);
			timestamp = System.currentTimeMillis();
		}

	}
}
